#!/usr/local/bin/php
<?php
require_once 'common.php';

global $logger;
global $dbOAIICust;
global $dbOAIICode;
global $codeModel;

$options = getopt('a:f:g:s');
if (empty($options)) {
    $logger->err("usage: " . basename(__FILE__) . " [-a import|delete] [-f app_list_file|-g app_id] -s");
    exit();
}
if (isset($options['a'])) {
    $action = $options['a'];
} else {
    $action = 'import';
}
if (!in_array($action, array('import', 'delete'))) {
    $logger->err("wrong action");
    exit();
}
if (isset($options['f'])) {
    $contents = file_get_contents($options['f']);
    if ($contents === false) {
        $logger->err("get file contents failed");
        exit();
    }
} else if (isset($options['g'])) {
    $contents = $options['g'];
} else {
    $logger->err("no app specified");
    exit();
}
if (isset($options['s'])) {
	$checkConflict = false;
} else {
	$checkConflict = true;
}

$rows = explode("\n", trim($contents));
if ($action == 'import') {
    foreach ($rows as $row) {
        $row = explode("\t", trim($row));
        $companyId = isset($row[0]) ? intval($row[0]) : 0;
        
        $sql = "SELECT t.SERVICE_ID,t.STATUS,t.SERVICE_NAME,t.SERVICE_CODE,t.SP_ID,t.NOTES,
        	TO_CHAR(t.UPDATETIME, 'YYYY-MM-DD HH24:MI:SS') AS UPDATETIME, 
        	t2.SP_CODE
        	FROM TBCODESERVICE t LEFT JOIN TBCODESP t2 ON (t.SP_ID=t2.SP_ID) 
        	WHERE SERVICE_CODE=:appId AND t.SP_ID>0";
        $st = oci_parse($dbOAIICust, $sql);
        oci_bind_by_name($st, ':appId', $companyId);
        if (!oci_execute($st)) {
            $e = oci_error($st);
            $logger->err("oci_execute failed: code-{$e['code']} message-{$e['message']} sql-{$e['sqltext']}");
            continue;
        }
        $service = oci_fetch_assoc($st);
        if (!$service) {
            $logger->err("app not exists: app-$companyId");
            continue;
        }
	    $app = $codeModel->getApp($companyId, OaAppModel::APP_CONFIG_ENV_PRODUCTION);
	    if ($checkConflict) {
		    if ($app && $app['SERVICE_NAME'] != $service['SERVICE_NAME']) {
		        $logger->err("app name conflicted: app-$companyId code_name-{$app['SERVICE_NAME']} cust_name-{$service['SERVICE_NAME']}");
	            continue;
		    }
		    $appByName = $codeModel->getAppByName($service['SERVICE_NAME'], OaAppModel::APP_CONFIG_ENV_PRODUCTION);
		    if ($appByName && $appByName['SERVICE_ID'] != $service['SERVICE_CODE']) {
		        $logger->err("app id conflicted: app-{$service['SERVICE_NAME']} code_id-{$appByName['SERVICE_ID']} cust_id-{$service['SERVICE_CODE']}");
	            continue;
		    }
	    }
        if ($app) {
            $logger->info("app already imported: app-$companyId");
            continue;
        } 
        
        // 导入游戏所属商户
        if (!importCompany($service['SP_CODE'], $checkConflict)) {
            $logger->err("import company failed: company-{$service['SP_CODE']} app-$companyId");
            continue;
        }
        
        // 导入游戏
        if (!$codeModel->addApp($service['SERVICE_CODE'], $service['SERVICE_NAME'], 
            $service['SP_CODE'], $service['STATUS'] + 1, $service['NOTES'], array(
                'IS_FROM_OA' => 2,
                'UPDATETIME' => $service['UPDATETIME']
            ), OaAppModel::APP_CONFIG_ENV_PRODUCTION)) {
            $logger->err("import app failed: app-$companyId");
            continue;
        }
        
        // 导入游戏区
        $sql = "SELECT AREA_ID,STATUS,AREA_NAME,AREA_CODE,SERVICE_ID,NOTES,REGIONFLAG,
        	SEEFLAG,VIRTUALFLAG,TO_CHAR(UPDATETIME, 'YYYY-MM-DD HH24:MI:SS') AS UPDATETIME,
        	TO_CHAR(BEGINTIME, 'YYYY-MM-DD HH24:MI:SS') AS BEGINTIME,
        	TO_CHAR(ENDTIME, 'YYYY-MM-DD HH24:MI:SS') AS ENDTIME,
        	TO_CHAR(SHOWBEGINTIME, 'YYYY-MM-DD HH24:MI:SS') AS SHOWBEGINTIME,
        	TO_CHAR(SHOWENDTIME, 'YYYY-MM-DD HH24:MI:SS') AS SHOWENDTIME
        	FROM TBCODEAREA WHERE SERVICE_ID=:serviceId ORDER BY AREA_CODE";
        $st = oci_parse($dbOAIICust, $sql);
        oci_bind_by_name($st, ':serviceId', $service['SERVICE_ID']);
        if (!oci_execute($st)) {
            $e = oci_error($st);
            $logger->err("oci_execute failed: code-{$e['code']} message-{$e['message']} sql-{$e['sqltext']}");
            continue;
        }
        oci_fetch_all($st, $areas, null, null, OCI_FETCHSTATEMENT_BY_ROW + OCI_ASSOC);
        foreach ($areas as $area) {
            if (!$codeModel->addArea($service['SERVICE_CODE'], $area['AREA_CODE'],
                $area['AREA_NAME'], $area['STATUS'] + 1, $area['NOTES'], array(
                    'REGIONFLAG' => $area['REGIONFLAG'],
                    'SEEFLAG' => $area['SEEFLAG'],
                    'VIRTUALFLAG' => $area['VIRTUALFLAG'],
                    'BEGINTIME' => $area['BEGINTIME'],
                    'ENDTIME' => $area['ENDTIME'],
                    'SHOWBEGINTIME' => $area['SHOWBEGINTIME'],
                    'SHOWENDTIME' => $area['SHOWENDTIME'],
                    'UPDATETIME' => $area['UPDATETIME'],
                ), OaAppModel::APP_CONFIG_ENV_PRODUCTION)) {
                $logger->err("import area failed: app-$companyId, area-{$area['AREA_CODE']}");
                continue;
            }
            $logger->info("import area succeed: app-$companyId, area-{$area['AREA_CODE']}");
        
            // 导入游戏组
            $sql = "SELECT GROUP_ID,STATUS,GROUP_NAME,GROUP_CODE,AREA_ID,NOTES,
            	SEEFLAG,VIRTUALFLAG,TO_CHAR(UPDATETIME, 'YYYY-MM-DD HH24:MI:SS') AS UPDATETIME,
            	TO_CHAR(BEGINTIME, 'YYYY-MM-DD HH24:MI:SS') AS BEGINTIME,
            	TO_CHAR(ENDTIME, 'YYYY-MM-DD HH24:MI:SS') AS ENDTIME,
            	TO_CHAR(SHOWBEGINTIME, 'YYYY-MM-DD HH24:MI:SS') AS SHOWBEGINTIME,
            	TO_CHAR(SHOWENDTIME, 'YYYY-MM-DD HH24:MI:SS') AS SHOWENDTIME
            	FROM TBCODEGROUP WHERE AREA_ID=:areaId ORDER BY GROUP_CODE";
            $st = oci_parse($dbOAIICust, $sql);
            oci_bind_by_name($st, ':areaId', $area['AREA_ID']);
            if (!oci_execute($st)) {
                $e = oci_error($st);
                $logger->err("oci_execute failed: code-{$e['code']} message-{$e['message']} sql-{$e['sqltext']}");
                continue;
            }
            oci_fetch_all($st, $groups, null, null, OCI_FETCHSTATEMENT_BY_ROW + OCI_ASSOC);
            foreach ($groups as $group) {
                if (!$codeModel->addGroup($service['SERVICE_CODE'], $area['AREA_CODE'],
                    $group['GROUP_CODE'], $group['GROUP_NAME'], $group['STATUS'] + 1, 
                    $group['NOTES'], array(
                        'SEEFLAG' => $group['SEEFLAG'],
                        'VIRTUALFLAG' => $group['VIRTUALFLAG'],
                        'BEGINTIME' => $group['BEGINTIME'],
                        'ENDTIME' => $group['ENDTIME'],
                        'SHOWBEGINTIME' => $group['SHOWBEGINTIME'],
                        'SHOWENDTIME' => $group['SHOWENDTIME'],
                        'UPDATETIME' => $group['UPDATETIME'],
                    ), OaAppModel::APP_CONFIG_ENV_PRODUCTION)) {
                    $logger->err("import group failed: app-$companyId, area-{$area['AREA_CODE']}, group-{$group['GROUP_CODE']}");
                    continue;
                }
                $logger->info("import group succeed: app-$companyId, area-{$area['AREA_CODE']}, group-{$group['GROUP_CODE']}");
            }
        }
        $logger->info("import app succeed: app-$companyId");
    }
} else if ($action == 'delete') {
    foreach ($rows as $row) {
        $row = explode("\t", trim($row));
        $companyId = isset($row[0]) ? intval($row[0]) : 0;
        
        $app = $codeModel->getApp($companyId, OaAppModel::APP_CONFIG_ENV_PRODUCTION);
        if (!$app) {
            $logger->err("app not exists: app-$companyId");
            continue;
        }
        if ($app['IS_FROM_OA'] != 2) {
            $logger->err("app from oa: app-$companyId");
            continue;
        }
        
        if (!$codeModel->deleteApp($companyId, OaAppModel::APP_CONFIG_ENV_PRODUCTION)) {
            $logger->err("delete app failed: app-$companyId");
            continue;
        }
        $logger->info("delete app succeed: app-$companyId");
    }
}
